<template>
  <div class="nav-bar" v-nav-current="{className: 'nav-item', activeClass: 'nav-current', curIdx}" @click="navClick($event)">
    <div class="scroll-wrapper">
      <div class="nav-wrapper" :style="`width: ${navData.length * .8}rem`">
        <nav-item v-for="(item, index) of navData" :key="index" :item="item" :index="index"></nav-item>
      </div>
    </div>
  </div>
</template>

<script>
import navData from '@/datas/nav';
import NavItem from './Item';
import { ref } from 'vue';
import { navCurrent } from '@/directives';
import { useStore } from 'vuex';
import getData from '@/services';

export default {
  name: 'NavBar',
  components: {
    NavItem
  },
  directives: {
    navCurrent
  },

  setup () {
    // const 定义的引用类型数据可以改变值，基本类型则会报错
    const curIdx = ref(0),
          store = useStore();
    
    const navClick = (e) => {
      const tar = e.target,
            idx = tar.dataset.index,
            consName = tar.innerText;
      
      // 下标不一样时再请求数据
      if(curIdx.value !== idx) {
        // ref定义的数据，注意取值
        curIdx.value = idx;
        store.commit('setConsName', consName);
        getData(store);
      }
    }
    return {
      navData,
      curIdx,
      navClick
    }
  }
}
</script>

<style lang='scss' scoped>
.nav-bar {
  position: fixed;
  top: .44rem;
  left: 0;
  z-index: 1;
  width: 100%;
  height: .38rem;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  background-color: #fff;
  overflow: hidden;

  .scroll-wrapper {
    height: .46rem;
    overflow-x: auto;

    .nav-wrapper {
      display: flex;
      flex-direction: row;
      height: .42rem;
    }
  }
}
</style>